package com.warm.demo.mf.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryChain;
import com.warm.demo.mf.api.dto.TestLeaveDto;
import com.warm.demo.mf.api.vo.TestLeaveVo;
import com.warm.demo.mf.domain.TestLeave;
import com.warm.demo.mf.mapper.TestLeaveMapper;
import com.warm.demo.mf.service.ITestLeaveService;
import com.warm.mf.core.domain.QueryParam;
import com.warm.mf.core.page.TableDataInfo;
import com.warm.mf.core.service.impl.BaseServiceImpl;
import org.noear.solon.annotation.Component;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;

import static com.warm.demo.mf.convert.TestLeaveC.testLeaveC;
import static com.warm.demo.mf.domain.table.TestLeaveTableDef.test_leave;
import static com.warm.mf.core.domain.QueryParam.getPage;

/**
 * OA 请假申请Service业务层处理
 *
 * @author warm
 * @date 2023-09-04
 */
@Component
public class TestLeaveServiceImpl extends BaseServiceImpl<TestLeaveMapper, TestLeave> implements ITestLeaveService {


    @Override
    public TestLeaveVo selectById(Long id) {
        TestLeave entity = getMapper().selectOneById(id);
        return testLeaveC.convert(entity);
    }

    @Override
    public TableDataInfo<TestLeaveVo> selectPage(QueryParam queryParam, TestLeaveDto dto) {
        Page<TestLeaveVo> page = buildQuery(dto).pageAs(getPage(queryParam), TestLeaveVo.class);
        if (CollUtil.isEmpty(page.getRecords())) {
            page.setRecords(Collections.emptyList());
        }
        return TableDataInfo.build(page);
    }

    @Override
    public List<TestLeaveVo> selectList(TestLeaveDto dto) {
        return buildQuery(dto).listAs(TestLeaveVo.class);
    }

    public QueryChain<TestLeave> buildQuery(TestLeaveDto dto) {
        Map<String, Object> params = dto.getParams();
        return this.queryChain()
                .where(test_leave.type.eq(dto.getType()))
                .and(test_leave.day.eq(dto.getDay()))
                .and(test_leave.flow_status.eq(dto.getFlowStatus()))
                .and(test_leave.create_by.eq(dto.getCreateBy()))
                .and(test_leave.create_time.between(params.get("beginCreateTime"), params.get("endCreateTime"))
                        .when(!ObjectUtil.hasNull(params.get("beginCreateTime"), params.get("endCreateTime"))));
    }

    @Override
    public int insertByDto(TestLeaveDto dto) {
        TestLeave entity = testLeaveC.convert(dto);
        return getMapper().insertSelective(entity);
    }

    @Override
    public int updateByDto(TestLeaveDto dto) {
        TestLeave entity = testLeaveC.convert(dto);
        return getMapper().update(entity);
    }

    @Override
    public int deleteByIds(Long[] ids) {
        return getMapper().deleteBatchByIds(Arrays.asList(ids));
    }
}
